<template>
  <div class="page-content">
    <ElForm :model="queryForm" :inline="true">
      <!-- 第一行：基础筛选 -->
      <ElRow :gutter="16" style="margin-bottom: 16px">
        <ElCol :xs="24" :sm="8" :md="6" :lg="5">
          <ElFormItem label="预约号">
            <ElInput
              v-model="queryForm.bookingNo"
              placeholder="请输入预约号"
              clearable
              style="min-width: 200px"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :xs="24" :sm="8" :md="6" :lg="4">
          <ElFormItem label="手机号">
            <ElInput
              v-model="queryForm.phone"
              placeholder="请输入手机号"
              clearable
              style="min-width: 150px"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :xs="24" :sm="8" :md="6" :lg="5">
          <ElFormItem label="场地类型">
            <ElSelect
              v-model="queryForm.venueType"
              placeholder="请选择场地类型"
              clearable
              style="width: 100%; min-width: 200px"
            >
              <ElOption label="亲子垂钓" value="family_fishing" />
              <ElOption label="路亚钓鱼" value="lure_fishing" />
              <ElOption label="森林瑜伽" value="forest_yoga" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :xs="24" :sm="8" :md="6" :lg="4">
          <ElFormItem label="预约状态">
            <ElSelect
              v-model="queryForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 100%; min-width: 150px"
            >
              <ElOption label="待确认" value="pending" />
              <ElOption label="已确认" value="confirmed" />
              <ElOption label="已取消" value="cancelled" />
              <ElOption label="已拒绝" value="rejected" />
              <ElOption label="已完成" value="completed" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <!-- 第二行：高级筛选 -->
      <ElRow :gutter="16" style="margin-bottom: 16px">
        <ElCol :xs="24" :sm="8" :md="6" :lg="4">
          <ElFormItem label="时间段">
            <ElSelect
              v-model="queryForm.timeSlot"
              placeholder="请选择时间段"
              clearable
              style="width: 100%; min-width: 150px"
            >
              <ElOption label="上午段" value="morning" />
              <ElOption label="下午段" value="afternoon" />
              <ElOption label="全天段" value="full_day" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :xs="24" :sm="8" :md="6" :lg="9">
          <ElFormItem label="预约日期">
            <ElDatePicker
              v-model="queryForm.bookingDate"
              type="date"
              placeholder="选择预约日期"
              style="width: 100%; min-width: 200px"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
            />
          </ElFormItem>
        </ElCol>

        <ElCol :xs="24" :sm="8" :md="6" :lg="6">
          <ElFormItem>
            <ElSpace :size="12">
              <ElButton type="primary" @click="handleSearch" v-ripple>搜索</ElButton>
              <ElButton @click="resetQuery" v-ripple>重置</ElButton>
              <ElButton type="success" @click="showAvailableSlotsDialog" v-ripple>
                查看可用时间段
              </ElButton>
            </ElSpace>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <ArtTable
      :data="bookingList"
      :loading="loading"
      :total="pagination.total"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :show-pagination="true"
      :hide-on-single-page="false"
      index
    >
      <template #default>
        <ElTableColumn label="预约号" prop="bookingNo" min-width="160" />
        <ElTableColumn label="用户信息" min-width="120">
          <template #default="scope">
            <div class="user-info">
              <div class="user-nick">{{ scope.row.userNickName || '-' }}</div>
              <div class="user-openid">{{ scope.row.openid.substring(0, 12) }}...</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="场地类型" prop="venueType" width="120">
          <template #default="scope">
            <ElTag :type="getVenueTagType(scope.row.venueType)">
              {{ getVenueName(scope.row.venueType) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="预约日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.bookingDate, 'date') }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="时间段" prop="timeSlot" width="150">
          <template #default="scope">
            {{ getTimeSlotName(scope.row.timeSlot) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="状态" prop="status" width="100">
          <template #default="scope">
            <ElTag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="备注" prop="remark" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="创建时间" prop="createTime" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn fixed="right" label="操作" width="200">
          <template #default="scope">
            <ElSpace :size="8">
              <ElButton type="primary" link @click="showDetailDialog(scope.row)">详情</ElButton>
              <ElButton
                v-if="scope.row.status === 'pending'"
                type="success"
                link
                @click="handleConfirm(scope.row)"
              >
                确认
              </ElButton>
              <ElButton
                v-if="scope.row.status === 'pending'"
                type="danger"
                link
                @click="showRejectDialog(scope.row)"
              >
                拒绝
              </ElButton>
              <ElButton
                v-if="scope.row.status === 'confirmed'"
                type="primary"
                link
                @click="handleComplete(scope.row)"
              >
                完成
              </ElButton>
            </ElSpace>
          </template>
        </ElTableColumn>
      </template>
    </ArtTable>

    <!-- 预约详情弹窗 -->
    <ElDialog v-model="detailDialogVisible" title="预约详情" width="700px" align-center>
      <div v-if="currentBooking" class="booking-detail">
        <ElDescriptions :column="2" border>
          <ElDescriptionsItem label="预约号">
            {{ currentBooking.bookingNo }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户昵称">
            {{ currentBooking.userNickName || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户openid">
            {{ currentBooking.openid }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="场地类型">
            <ElTag :type="getVenueTagType(currentBooking.venueType)">
              {{ getVenueName(currentBooking.venueType) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="预约日期">
            {{ formatDate(currentBooking.bookingDate, 'date') }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="时间段">
            {{ getTimeSlotName(currentBooking.timeSlot) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="入场券类型">
            {{ currentBooking.ticketType || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="预约状态">
            <ElTag :type="getStatusTagType(currentBooking.status)">
              {{ getStatusText(currentBooking.status) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="创建时间">
            {{ formatDate(currentBooking.createTime) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="更新时间">
            {{ formatDate(currentBooking.updateTime) }}
          </ElDescriptionsItem>
        </ElDescriptions>

        <div class="mt-4">
          <ElDescriptions :column="1" border>
            <ElDescriptionsItem label="备注">
              {{ currentBooking.remark || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="取消原因" v-if="currentBooking.cancelReason">
              {{ currentBooking.cancelReason }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="拒绝原因" v-if="currentBooking.rejectReason">
              {{ currentBooking.rejectReason }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="场地描述">
              {{ getVenueDescription(currentBooking.venueType) }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="detailDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 拒绝预约弹窗 -->
    <ElDialog
      v-model="rejectDialogVisible"
      title="拒绝预约"
      width="500px"
      align-center
      :close-on-click-modal="false"
    >
      <ElForm ref="rejectFormRef" :model="rejectForm" :rules="rejectRules" label-width="100px">
        <ElFormItem label="拒绝原因" prop="reason">
          <ElInput
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因（5-500字符）"
            maxlength="500"
            show-word-limit
          />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="rejectDialogVisible = false">取消</ElButton>
          <ElButton type="danger" @click="handleReject" :loading="submitLoading">
            确认拒绝
          </ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 可用时间段弹窗 -->
    <ElDialog
      v-model="availableSlotsDialogVisible"
      title="查看可用时间段"
      width="600px"
      align-center
    >
      <ElForm :model="availableSlotsForm" label-width="100px">
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="场地类型" required>
              <ElSelect
                v-model="availableSlotsForm.venueType"
                placeholder="请选择场地类型"
                style="width: 100%"
              >
                <ElOption label="亲子垂钓" value="family_fishing" />
                <ElOption label="路亚钓鱼" value="lure_fishing" />
                <ElOption label="森林瑜伽" value="forest_yoga" />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="预约日期" required>
              <ElDatePicker
                v-model="availableSlotsForm.bookingDate"
                type="date"
                placeholder="选择预约日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElFormItem>
          <ElButton type="primary" @click="queryAvailableSlots">查询</ElButton>
        </ElFormItem>
      </ElForm>

      <div v-if="availableSlots" class="available-slots-result">
        <ElAlert
          :title="`${getVenueName(availableSlots.venueType)} - ${availableSlots.bookingDate} - 总容量: ${availableSlots.capacity}人`"
          type="info"
          :closable="false"
          style="margin-bottom: 16px"
        />
        <ElRow :gutter="16">
          <ElCol v-for="(slot, key) in availableSlots.availableSlots" :key="key" :span="8">
            <ElCard
              :class="{ 'available-card': slot.available, 'unavailable-card': !slot.available }"
              shadow="hover"
            >
              <div class="slot-info">
                <div class="slot-title">{{ getTimeSlotName(slot.timeSlot) }}</div>
                <div class="slot-time">{{ slot.timeRange }}</div>
                <div class="slot-status">
                  <ElTag :type="slot.available ? 'success' : 'danger'">
                    {{ slot.available ? '可预约' : '已满' }}
                  </ElTag>
                </div>
                <div class="slot-remaining">剩余: {{ slot.remaining }}人</div>
              </div>
            </ElCard>
          </ElCol>
        </ElRow>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="availableSlotsDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import {
    BookingService,
    type Booking,
    type BookingListParams,
    type VenueType,
    type AvailableSlots,
    getVenueName,
    getVenueDescription,
    getTimeSlotName,
    getStatusText,
    getStatusTagType,
    getVenueTagType
  } from '@/api/bookingApi'

  defineOptions({ name: 'BookingManage' })

  // 响应式数据
  const loading = ref(false)
  const submitLoading = ref(false)
  const detailDialogVisible = ref(false)
  const rejectDialogVisible = ref(false)
  const availableSlotsDialogVisible = ref(false)
  const rejectFormRef = ref<FormInstance>()
  const currentBooking = ref<Booking | null>(null)
  const availableSlots = ref<AvailableSlots | null>(null)

  // 查询表单
  const queryForm = reactive<BookingListParams & { bookingNo?: string }>({
    bookingNo: '',
    openid: '',
    phone: '',
    venueType: undefined,
    status: undefined,
    timeSlot: undefined,
    bookingDate: undefined,
    sort: 'createTime',
    order: 'desc'
  })

  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 10,
    total: 0
  })

  // 预约列表
  const bookingList = ref<Booking[]>([])

  // 拒绝表单
  const rejectForm = reactive({
    reason: ''
  })

  // 可用时间段查询表单
  const availableSlotsForm = reactive({
    venueType: '',
    bookingDate: ''
  })

  // 拒绝表单验证规则
  const rejectRules = reactive<FormRules>({
    reason: [
      { required: true, message: '请输入拒绝原因', trigger: 'blur' },
      { min: 5, max: 500, message: '长度在 5 到 500 个字符', trigger: 'blur' }
    ]
  })

  // 获取预约列表
  const getBookingList = async () => {
    try {
      loading.value = true
      const params: BookingListParams = {
        page: pagination.page,
        size: pagination.size,
        ...queryForm
      }
      // 移除空值
      Object.keys(params).forEach((key) => {
        if (
          params[key as keyof BookingListParams] === '' ||
          params[key as keyof BookingListParams] === undefined
        ) {
          delete params[key as keyof BookingListParams]
        }
      })

      const response = await BookingService.getBookingList(params)
      if (response.code === 200) {
        bookingList.value = response.data
        pagination.total = response.total
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error('获取预约列表失败')
      console.error('获取预约列表失败:', error)
      bookingList.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getBookingList()
  }

  // 重置查询
  const resetQuery = () => {
    Object.assign(queryForm, {
      bookingNo: '',
      openid: '',
      phone: '',
      venueType: undefined,
      status: undefined,
      timeSlot: undefined,
      bookingDate: undefined,
      sort: 'createTime',
      order: 'desc'
    })
    pagination.page = 1
    getBookingList()
  }

  // 分页处理
  const handleSizeChange = (val: number) => {
    pagination.size = val
    pagination.page = 1
    getBookingList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    getBookingList()
  }

  // 显示预约详情
  const showDetailDialog = async (row: Booking) => {
    try {
      const response = await BookingService.getBookingDetail(row._id!)
      currentBooking.value = response.data
      detailDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取预约详情失败')
      console.error('获取预约详情失败:', error)
    }
  }

  // 确认预约
  const handleConfirm = (row: Booking) => {
    ElMessageBox.confirm('确定确认该预约吗？', '确认预约', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }).then(async () => {
      try {
        await BookingService.confirmBooking(row._id!)
        ElMessage.success('确认成功')
        getBookingList()
      } catch (error) {
        ElMessage.error('确认失败')
        console.error('确认失败:', error)
      }
    })
  }

  // 显示拒绝弹窗
  const showRejectDialog = (row: Booking) => {
    currentBooking.value = row
    rejectForm.reason = ''
    rejectDialogVisible.value = true
  }

  // 拒绝预约
  const handleReject = async () => {
    if (!rejectFormRef.value || !currentBooking.value) return

    try {
      await rejectFormRef.value.validate()
      submitLoading.value = true

      await BookingService.rejectBooking(currentBooking.value._id!, {
        reason: rejectForm.reason
      })

      ElMessage.success('拒绝成功')
      rejectDialogVisible.value = false
      getBookingList()
    } catch (error) {
      ElMessage.error('拒绝失败')
      console.error('拒绝失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  // 完成预约
  const handleComplete = (row: Booking) => {
    ElMessageBox.confirm('确定将该预约标记为完成吗？', '完成预约', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'primary'
    }).then(async () => {
      try {
        await BookingService.completeBooking(row._id!)
        ElMessage.success('操作成功')
        getBookingList()
      } catch (error) {
        ElMessage.error('操作失败')
        console.error('操作失败:', error)
      }
    })
  }

  // 显示可用时间段弹窗
  const showAvailableSlotsDialog = () => {
    availableSlotsForm.venueType = ''
    availableSlotsForm.bookingDate = ''
    availableSlots.value = null
    availableSlotsDialogVisible.value = true
  }

  // 查询可用时间段
  const queryAvailableSlots = async () => {
    if (!availableSlotsForm.venueType || !availableSlotsForm.bookingDate) {
      ElMessage.warning('请选择场地类型和预约日期')
      return
    }

    try {
      const response = await BookingService.getAvailableSlots(
        availableSlotsForm.venueType as VenueType,
        availableSlotsForm.bookingDate
      )
      if (response.code === 200) {
        availableSlots.value = response.data
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error('查询可用时间段失败')
      console.error('查询可用时间段失败:', error)
    }
  }

  // 格式化时间
  const formatDate = (timestamp?: number, type: 'datetime' | 'date' = 'datetime') => {
    if (!timestamp) return '-'

    try {
      const date = new Date(timestamp * 1000)
      if (isNaN(date.getTime())) {
        return timestamp.toString()
      }

      if (type === 'date') {
        return date
          .toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
          })
          .replace(/\//g, '-')
      }

      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
        .replace(/\//g, '-')
    } catch (error) {
      console.error('时间格式化错误:', error, timestamp)
      return timestamp?.toString() || '-'
    }
  }

  // 生命周期
  onMounted(() => {
    getBookingList()
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .user-info {
      .user-nick {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .user-openid {
        margin-top: 2px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }

    .booking-detail {
      .mt-4 {
        margin-top: 16px;
      }
    }

    .available-slots-result {
      margin-top: 16px;

      .available-card {
        border-color: var(--el-color-success-light-7);

        &:hover {
          border-color: var(--el-color-success);
        }
      }

      .unavailable-card {
        border-color: var(--el-color-danger-light-7);

        &:hover {
          border-color: var(--el-color-danger);
        }
      }

      .slot-info {
        text-align: center;

        .slot-title {
          margin-bottom: 8px;
          font-weight: 500;
          color: var(--el-text-color-primary);
        }

        .slot-time {
          margin-bottom: 8px;
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }

        .slot-status {
          margin-bottom: 8px;
        }

        .slot-remaining {
          font-size: 12px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
</style>
